$(function(){
    var request_url = new UrlSearch();
    var project_title = " ";
    if (request_url.title) {
        project_title = decodeURI(request_url.title);
    }
    if (p_type=="None"){
        p_type = 0;
    }
    // 题型定义：[name: "[中文名]", en_name: "英文名"，type: "题型", custom_attr: 子题型属性{}]
    var question_type_obj_list =
    [
        {"name":"[单选题]","en_name": "QUESTION_TYPE_SINGLE", "type":2, "custom_attr": {}},
        {"name":"[多选题]","en_name": "QUESTION_TYPE_MULTIPLE", "type":3, "custom_attr": {}},
        {"name":"[单行填空题]","en_name": "QUESTION_TYPE_BLANK", "type":6, "custom_attr": {"blank_type": "single"}},
        {"name":"[多行填空题]","en_name": "QUESTION_TYPE_BLANK", "type":6, "custom_attr": {}}
    ];
    // 使用codemirror编辑器
    var default_v = project_title + "\n感谢您能抽出几分钟时间来参加本次答题，现在我们就马上开始吧！\n" + "\n" + "您经常创建什么类型的项目？[单选题]\n" + "\n" + "问卷调研\n" + "表单报名\n" + "测评考试\n" + "\n" + "您使用过问卷网哪款应用？[多选题]\n" + "抽奖\n" + "配额\n" + "投票墙\n" + "微信红包\n" + "微信签到\n" + "自定义域名\n" + "隐藏问卷网标志\n" + "限定手机号答题\n" + "\n" + "您的姓名：[单行填空题]\n" + "\n" + "请填写您的问题和建议：[多行填空题]";
    var codem = CodeMirror(document.getElementById('editCon'),{
        mode: "",                 //模式
        value: default_v,         //初始值
        lineWrapping : false,     //不自动换行
        lineNumbers: false,       //不添加行号
        fixedGutter: false,        //根据编辑器内容固定在左侧
    });
    codem.on("change", function(){
        dataSetFn();
    });
    var dataSet = {"title": "", "welcome": "", "question_list": [], "type_id": request_url.project_func, "p_type": p_type};
    var widget_list = [];
    dataSetFn();
    // 生成数据Fn
    function dataSetFn(){
        dataSet = {"title": "", "welcome": "", "question_list": [], "type_id": request_url.project_func, "p_type": p_type};
        delWidget();
        var line_list = codem.getValue().split('\n');
        if (line_list.join("").length===0){
            insetWidget(0, "请输入标题和题目");
        }else{
            line_list.push("line_end");
            var welcome = "";
            var question = {};
            $.each(line_list,function(index, value){
                if (value === ""){return;}
                if (dataSet.title === ""){
                    dataSet.title=value;
                }else{
                    var type_dict = get_type(value);
                    if (type_dict.type){
                        if(dataSet.question_list.length === 0){
                            dataSet.welcome = welcome;
                        }
                        if (question.option_list){
                            save_question(question);
                        }
                        question = {"title": type_dict.txt, "type": type_dict.type, "en_name": type_dict.en_name, "custom_attr": type_dict.custom_attr, option_list: [], index_line: index};
                    }else{
                        if (value != "line_end"){
                            if(!question.option_list){
                                welcome += type_dict.txt + ' ';
                            }else{
                                var option_obj = {'title': type_dict.txt};
                                question.option_list.push(option_obj);
                            }
                        }else{
                            question.type ? save_question(question) : dataSet.welcome=welcome;
                        }
                    }
                }
                if (dataSet.question_list.length > 100){
                    insetWidget(0, "导入题目最多支持100个");
                    dataSet.question_list = dataSet.question_list.slice(0, 100);
                    return false;
                }
            });
        }
        if (widget_list.length > 0) {
            codem.scrollTo(1, codem.getScrollInfo().top);
        }
        var zxbox = document.getElementById('outbox').innerHTML;
        var conStr = juicer(zxbox, {"data":dataSet});
        $('.previewCon').html(conStr);
    }
    // 判断题型
    function get_type(str) {
        var type_dict = {};
        for (var i=0; i<question_type_obj_list.length; i++){
            var typeobj = question_type_obj_list[i];
            if (str.slice(-typeobj.name.length) == typeobj.name){
              type_dict.txt = str.slice(0, str.length-typeobj.name.length);
              type_dict.type = typeobj.type;
              type_dict.en_name = typeobj.en_name;
              type_dict.custom_attr = typeobj.custom_attr;
              break;
          }
      }
      if (type_dict.type === undefined){
        type_dict.txt = str;
        type_dict.type = "";
        type_dict.en_name = "";
        type_dict.custom_attr = {};
      }
      return type_dict;
    }
    // 保存题型及验证
    function save_question(question){
        if ($.inArray(question.en_name, ["QUESTION_TYPE_SINGLE", "QUESTION_TYPE_MULTIPLE"]) !=-1 ){
            if (question.option_list.length === 0){
                insetWidget(question.index_line, "请输入至少一个选项");
            }else if (question.option_list.length > 100){
                question.option_list = question.option_list.slice(0, 100);
                insetWidget(question.index_line, "选项不能超过100个");
            }
        }else if (question.en_name == "QUESTION_TYPE_BLANK"){
            if (question.option_list.length > 0){
                insetWidget(question.index_line, "填空题不需要设置选项");
            }
        }
        dataSet.question_list.push(question);
    }
    // 插入提示语
    function insetWidget(line, errorTxt){
        var nd = document.createElement("div");
        nd.setAttribute('class','CodeMirror-linewidget');
        nd.setAttribute('cm-ignore-events',true);
        var nd_1 = document.createElement("div");
        nd_1.setAttribute('class','text-to-survey-editor-error');
        var t = document.createTextNode(errorTxt);
        nd_1.appendChild(t);
        nd.appendChild(nd_1);
        var xz = codem.addLineWidget(line,nd,{noHScroll: true});
        widget_list.push([xz, line]);
    }
    // 删除提示语
    function delWidget(){
      $.each(widget_list, function(i, j){
        j[0].clear();
      });
      widget_list = [];
    }
    // 预览页点击事件
    $(".QUESTION_TYPE_SINGLE").live("click", function(){
        $(this).parents(".options").find("i").removeClass("active");
        $(this).find("i").addClass('active');
    });
    $(".QUESTION_TYPE_MULTIPLE").live("click", function(){
        $(this).find("i").toggleClass('active');
    });
    // 查看帮助
    $(".textProject .help_bt").live("click", function(){
        maptss(802, 571, "帮助提示", ".helpCon");
    });
    // 生成问卷
    $(".textProject .create_bt").live("click", function(){
        if (widget_list.length > 0){
            maptss(420, "auto", "导入提示", ".erorr_prompt");
            return false;
        }
        loadMack({off: 'on', Limg: 0, text: '加载中...', set: 0 });
        $("#create_project input[name=project_json]").val(JSON.stringify(dataSet));
        ajaxSubmit("#create_project");
    });
    // 点击返回
    $(".head_nav .back").live("click", function(){
        maptss(420, "auto", "导入提示", ".report_prompt");
    });
    $(".tccCon_a .go_back").live("click", function(){
        $(window).unbind("beforeunload");
        window.location.href = $(".head_nav .back").attr("go_url");
    });
    $(".tccCon_a .uniteC, .tccCon_a .close_bt").live("click", function(){
        $(".jsbox_close").click();
        if ($(this).hasClass("close_bt")){
            codem.scrollTo(0, widget_list[0][1]*21);
        }
    });
    $(window).bind("beforeunload", function(){
        return "您要放弃当前编辑的题目吗？";
    });
});
//弹出框打包配置
function maptss(w, h, title, obj) {
    var con =$(obj).parent().html();
    var FixedTop = 240;
    if (h != "auto") {
        var zh = document.documentElement.clientHeight || document.body.clientHeight;
        FixedTop = (zh - h) / 2 + 50;
    }
    var wb = new jsbox({
        onlyid: "maptss",
        title: title,
        conw: w,
        conh: h,
        FixedTop: FixedTop,
        Opacity: .4,
        loads: true,
        content: con,
        range: false,
        mack: true
    }).show();
}
function createProjectFn(ret){
    if (!ret.msg){
        createProjectPollingFn(ret.fingerprint);
    }else{
        $(".loadMack, .loadCon").remove();
        loadMack({off: 'on', Limg: 0, text: ret.msg, set: 2000 });
    }
}
function createProjectPollingFn(fingerprint){
    var timestamp = new Date().getTime();
    var ret = JSON.parse($.ajax({
        url: '/edit/ajax/textproject/?'+timestamp,
        type: "GET",
        data: {
            'fingerprint': fingerprint,
            '_xsrf': $.cookie('_xsrf')
        },
        async: false
    }).responseText);
    if (!ret.continue_poll){
        $(window).unbind("beforeunload");
        window.location.href = "/edit/survey/"+ ret.project_id;
        return;
    }
    setTimeout("createProjectPollingFn('"+ fingerprint +"')", 3000);
}